//pages/first/commodities/commodities.js
const db = wx.cloud.database()
const commoditiesCollection = db.collection('commodities')
const favoriteCollection = db.collection('favorite')
const cartlistCollection = db.collection('cartlist')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    //初始化数据
    showModalStatus: false,//是否显示
    optionID: -1,//规格ID
    optionName: '',//规格文本
    optionPrice: 0,//价格
    optionStock: '',//库存
    num: 1,//默认购买数量

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      goodsID: options.goodsID,
      typeID: options.typeID,
      id: options.id
    });
    commoditiesCollection.doc(options.id).get({
      success: res => {
        console.log("成功获取商品类型信息", res.data.typeTitle)
        console.log("成功获取该类目下的商品信息", res.data.goods)
        this.setData({
          commodities: res.data.goods,
          typeTitle:res.data.typeTitle
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    favoriteCollection.get({
      success: res => {
        console.log("成功获取收藏内容", res.data)
        this.setData({
          favorite: res.data,
        })
      }
    })
    cartlistCollection.get({
      success: res => {
        console.log("成功获取购物车信息", res.data)
        this.setData({
          cartlist: res.data,
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /*预览轮播图函数*/
  previewImage: function (e) {
    var current = e.target.dataset.src;
    var goodsID = e.target.dataset.gid;
    wx.previewImage({
      current: current, // 当前显示图片的http链接  
      urls: this.data.commodities[goodsID].swiperImages // 需要预览的图片http链接列表  
    })
  },

  /*点击“选择购买数量”触发显示对话框*/
   showOptions() {
    var showModalStatus1 = this.data.showModalStatus;
    this.setData({
      showModalStatus: !showModalStatus1
    })
  },

  /*显示对话框*/
  showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  /*隐藏对话框*/
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },

  /**
  * 读取库存数量
  */
  filter: function (e) {
    var id = e.currentTarget.dataset.id;
    var name = e.currentTarget.dataset.name;
    var price = e.currentTarget.dataset.price;
    var stock = e.currentTarget.dataset.stock;

    this.setData({
      optionID: id,
      optionName: name,
      optionPrice: price,
      optionStock: stock,
      num: 1
    });
  },
  /*控制购买数量+-值*/
  minusNum: function () {
    var num = this.data.num;
    if (num > 1) {
      num--;
    } else {
      wx.showToast({
        title: '不能再减了哦~',
        icon: 'none',
        duration: 1500
      });
    };
    var minusStatus = num <= 1 ? 'disabled' : 'normal';
    this.setData({
      num: num,
      minusStatus: minusStatus
    });
  },
  /**
   * 控制购买数量范围
   */
  bindManual: function (e) {
    var value = e.detail.value;
    var num = this.data.num;
    var stock = e.currentTarget.dataset.stock;
    if (value <= stock && value >= 1) {
      num = value;
      this.setData({
        num: num
      });
    } else {
      num = num;
      this.setData({
        num: num
      });
      if (value == 0) {
        wx.showToast({
          title: '购买数量不可为0哦！请重新输入',
          icon: 'none',
          duration: 2000
        });
      } else {
        wx.showToast({
          title: '购买数量超过库存数啦！请重新输入',
          icon: 'none',
          duration: 2000
        });
      };
    }
  },

  addNum: function (e) {
    var num = this.data.num;
    var stock = e.currentTarget.dataset.stock;
    if (num < stock) {
      num++;
    } else {
      wx.showToast({
        title: '超过库存量啦~',
        icon: 'none',
        duration: 1500
      });
    };
    var minusStatus = num >= stock ? 'disabled' : 'normal';
    this.setData({
      num: num,
      minusStatus: minusStatus
    });
  },
  /**
   * 底部固定按钮”去购物车“事件
   */
  goToCart: function (e) {
    wx.switchTab({
      url: '../../cart/cart',
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  /**
   * ”加入购物车“事件
   */
  addToCart(event) {
    var optionID = event.currentTarget.dataset.oid;
    if (optionID == -1) {
      wx.showToast({
        title: '还未选择套装呢~',
        icon: 'none',
        duration: 2000
      })
    } else {
      var id = this.data.id
      console.log(event.currentTarget.dataset)
      var typeID = event.currentTarget.dataset.tid;
      var goodsID = event.currentTarget.dataset.gid;
      var optionID = event.currentTarget.dataset.oid;
      var c = event.currentTarget.dataset.c;
      var num = event.currentTarget.dataset.num;
      var goodsTitle = c[goodsID - 1].goodsTitle;
      var optionName = c[goodsID - 1].options[optionID].name;
      var optionPrice = c[goodsID - 1].options[optionID].price;
      var optionStock = c[goodsID - 1].options[optionID].stock;
      var goodsImage = c[goodsID - 1].swiperImages[0];
      var goods_id = c[goodsID - 1].goods_id;
      var cartlist = this.data.cartlist;

      // console.log(goodsTitle,optionName,optionPrice,num)

      if (cartlist.length > 0) {
        for (var j in cartlist) {
          if (cartlist[j].goods_id == goods_id && cartlist[j].optionName == optionName) {
            var old = cartlist[j].num;
            var stock = cartlist[j].optionStock;
            var add = num;
            var now = parseInt(old) + parseInt(add);
            var _id = cartlist[j]._id;
            if (now > stock) {
              db.collection('cartlist').doc(_id).update({
                data: {
                  num: stock
                },
                success: console.log,
                fail: console.error
              })
              wx.showToast({
                title: '更新成功！',
                icon: 'success',
                duration: 3000
              })
              this.setData({
                showModalStatus: false
              })

            } else {
              db.collection('cartlist').doc(_id).update({
                data: {
                  num: now
                },
                success: console.log,
                fail: console.error
              })
              wx.showToast({
                title: '更新成功！',
                icon: 'success',
                duration: 3000
              })
            }
            return;
          }
        }
        cartlistCollection.add({
          data: {
            type_id: id,
            typeID: typeID,
            goodsID: goodsID,
            goodsTitle: goodsTitle,
            goodsImage: goodsImage,
            optionName: optionName,
            optionPrice: optionPrice,
            optionStock: optionStock,
            num: num,
            isSelect: false,
            goods_id: goods_id,
          },
          success(res) {
            // res 是一个对象，其中有 _id 字段标记刚创建的记录的 id
            console.log(res)
            wx.showToast({
              title: '添加成功！',
              icon: 'success',
              duration: 3000
            })
          },
          fail: console.error
        })

      } else {
        cartlistCollection.add({
          data: {
            type_id: id,
            typeID: typeID,
            goodsID: goodsID,
            goodsTitle: goodsTitle,
            goodsImage: goodsImage,
            optionName: optionName,
            optionPrice: optionPrice,
            optionStock: optionStock,
            num: num,
            isSelect: false,
            goods_id: goods_id,
          },
          success(res) {
            // res 是一个对象，其中有 _id 字段标记刚创建的记录的 id
            console.log(res)
            wx.showToast({
              title: '添加成功！',
              icon: 'success',
              duration: 3000
            })
          },
          fail: console.error
        })
      }
      this.setData({
        showModalStatus: false
      })
    }
  }, 
  /**
   * 添加到收藏事件
   */
  addToFavorite(e) {
    const typeID = e.currentTarget.dataset.tid;
    const goodsID = e.currentTarget.dataset.gid;
    let c = this.data.commodities;
    
    var id = this.data.id;
    var goodsTitle = c[goodsID - 1].goodsTitle;
    var goodsImage = c[goodsID - 1].swiperImages[0];
    var currentPrice = c[goodsID - 1].currentPrice;
    var goods_id = c[goodsID - 1].goods_id;
    var f = this.data.favorite;
    console.log(f)
    if (f.length > 0) {
      for (var j in f) {
        if (f[j].goods_id == goods_id) {
          wx.showToast({
            title: '您已收藏过本商品！',
            icon: 'none',
            duration: 3000
          });
          return;
        }
      }
      favoriteCollection.add({
        data: {
          type_id: id,
          typeID: typeID,
          goodsID: goodsID,
          goodsTitle: goodsTitle,
          goodsImage: goodsImage,
          currentPrice: currentPrice,
          goods_id: goods_id,
        },
        success(res) {
          // res 是一个对象，其中有 _id 字段标记刚创建的记录的 id
          console.log("成功收藏一个商品", res)
          wx.showToast({
            title: '收藏成功！',
            icon: 'success',
            duration: 3000
          })
        },
        fail: console.error
      })
    } else {
      favoriteCollection.add({
        data: {
          type_id: id,
          typeID: typeID,
          goodsID: goodsID,
          goodsTitle: goodsTitle,
          goodsImage: goodsImage,
          currentPrice: currentPrice,
          goods_id: goods_id,
        },
        success(res) {
          // res 是一个对象，其中有 _id 字段标记刚创建的记录的 id
          console.log("成功收藏一个商品", res)
          wx.showToast({
            title: '收藏成功！',
            icon: 'success',
            duration: 3000
          })
        },
        fail: console.error
      })

    }

  },
})